package com.minelx.serverandclient.stream.data;

import com.minelx.serverandclient.common.EnsuredString;
import com.minelx.serverandclient.stream.BytesIndexer;
import com.minelx.serverandclient.stream.divider.Generator;
import com.minelx.serverandclient.stream.divider.IndexedDividerFactory;

import java.util.Arrays;

public class Packet {

	private final byte[] data;

	private Packet(byte[] data) {
		this.data = data;
	}

	public byte[] getDataBytes() {
		return data;
	}

	public String getDataAsString() {
		return new String(data);
	}

	public Generator<StreamCache> serialize() {
		StreamCache cache = StreamCache.empty();
		return new Generator<>(
				(data, len) -> cache.render(data, 0, len),
				new IndexedDividerFactory(new BytesIndexer(data)).create(StreamCache.DATA_SIZE)
		);
	}

	public static Packet of(byte[] data) {
		return new Packet(data);
	}

	public static Packet of(String content) {
		return new Packet(content.getBytes());
	}

	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof Packet)) {
			return false;
		}
		return Arrays.equals(data, ((Packet) obj).data);
	}

	@Override
	public String toString() {
		return "Packet" + EnsuredString.of(Arrays.toString(data))
				.trimCap()
				.cap("(", ")")
				.toString();
	}
}


